package com.tencent.sr.iris.basic.saas.common.utils;

import cn.hutool.core.annotation.AnnotationUtil;
import lombok.extern.slf4j.Slf4j;

import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.Map;

/**
 * @author nixiaolin
 * @date 2023/2/7 18:07
 */
@Slf4j
public abstract class AnnotationUtils {

    /**
     * @param ele 
     * @param annoClass
     * @param annoAttrName
     * @param annoAttrVal
     * @param <A>
     */
    public static <A extends Annotation> void modifyAnnoAttr(AnnotatedElement ele, Class<A> annoClass,
                                                             String annoAttrName, Object annoAttrVal) {
        A annotation = AnnotationUtil.getAnnotation(ele, annoClass);
        if (annotation == null) {
            return;
        }

        try {
            InvocationHandler invocationHandler = Proxy.getInvocationHandler(annotation);
            Field memberValues = invocationHandler.getClass().getDeclaredField("memberValues");
            memberValues.setAccessible(true);

            Map memberValuesMap = (Map) memberValues.get(invocationHandler);
            memberValuesMap.put(annoAttrName, annoAttrVal);
        } catch (Exception e) {
            log.error("修改注解值异常：", e);
        }
    }
}
